package cn.cqvie.controller;

import cn.cqvie.common.R;
import cn.cqvie.dto.UserDTO;
import cn.cqvie.pojo.User;
import cn.cqvie.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/getMSG")
    public R<Page> getUsers(Integer page,Integer pageSize,String name){
        Page myPage=new Page(page,pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),User::getName,name);
        queryWrapper.orderByDesc(User::getId);
        userService.page(myPage,queryWrapper);
        return R.success(myPage);
    }
    @PostMapping("/editUser")
    public R<String> edit(@RequestBody User user){
        userService.updateById(user);
        return R.success("更新成功");
    }
    @DeleteMapping("/deleteUser")
    public R<String> delete(Long id){
        User user = userService.getById(id);
        if(user.getStatus()==1){
            return R.error("该用户账号正在使用中，删除失败");
        }else{
            userService.removeById(id);
            return R.success("删除成功");
        }
    }
    @PostMapping
    public R<String> saveUser(@RequestBody Object o){
        UserDTO userDTO = (UserDTO) JSON.parseObject(JSON.toJSONString(o), UserDTO.class);
        String code = (String) redisTemplate.opsForValue().get(userDTO.getEMail());
        if(userDTO.getCode().equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername,userDTO.getUsername());
            User user = userService.getOne(queryWrapper);
            if(user==null){
                userDTO.setStatus(1);
                userDTO.setEMail(userDTO.getEMail()+"@qq.com");
                userService.save(userDTO);
                redisTemplate.delete(userDTO.getEMail());
                return R.success("注册成功");
            }else{
                return R.error("用户已存在");
            }
        }
        return R.error("验证码错误");
    }
}
